package com.fms.fmsapi.utils;

import com.fms.fmsapi.entity.User;
import io.jsonwebtoken.*;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Date;
import java.util.UUID;

/**
 * token工具类
 */
public class JwtUtil {
    private static long time = 1000 * 60 * 60 * 24;//24小时
    private static  String sign = "zhangliwen";

    /**
     * 生成token
     * @param user
     * @return
     */
    public static String creatToken(User user){
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                //Header：头部
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "H5256")
                .claim("userId",user.getUuid())
                .setSubject("admin-test")
                .setExpiration(new Date(System.currentTimeMillis() + time))//Token的过期时间,从当前时间往后存活24小时
                .setId(UUID.randomUUID().toString())//id字段
                //sign:签名
                .signWith(SignatureAlgorithm.HS256,sign)//设置加密算法和签名
                //使用“.”连接成一个完整的字符串
                .compact();
        return jwtToken;
    }

    //验证token是否过期的方法
    public static boolean checkToken(String token){
        if(token == null || token.equals("")){
            return false;
        }
        try{
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(sign).parseClaimsJws(token);
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 从请求头中获取token
     * @param request
     * @return
     */
    public static String getToken(HttpServletRequest request){
        return request.getHeader("token");
    }

    public static String getUserId(String token){
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(sign).parseClaimsJws(token);
        Claims body = claimsJws.getBody();

        return (String) body.get("userId");
    }
}
